import React, { useContext, useEffect, useState } from 'react';
import { Outlet, useNavigate } from 'react-router-dom';
import { Layout, Menu } from 'antd';
import { Button } from 'antd-mobile';
import {
  MenuUnfoldOutlined,
  MenuFoldOutlined
} from '@ant-design/icons';
import DropdownCom from './Dropdown';
import { GlobalContext } from '../contexts/GlobalContext';
// 引入样式
import '../styles/AuthLayout.css';
import DefaultMenuData from "../mock/data/MenuData";
import DefaultRoleData from "../mock/data/RoleData";
import IconMap from "../utils/IconMap";

const { Header, Content, Footer, Sider } = Layout;

// 渲染侧边栏菜单的函数
const renderMenu = (menuItems, handleMenuClick) => (
    <Menu
        mode="inline"
        style={{ height: '100%', borderRight: 0 }}
        onClick={handleMenuClick}
        items={menuItems&&menuItems.map((item) => ({
          key: item.path,
          icon: IconMap[item.icon],
          label: item.title,
          children: item.children ? item.children.map((child) => ({
            key: child.path,
            icon: IconMap[child.icon],
            label: child.title,
          })) : null,
        }))}
    />
);

// 使用 useState 钩子初始化 menuItems 状态


export default function AuthLayout() {

  // 使用 useState 钩子初始化 menuItems 状态
  const [menuItems, setMenuItems] = useState([]);
    const globalContext = useContext(GlobalContext);
    const navigate = useNavigate();
    const [collapsed, setCollapsed] = useState(false); // 是否折叠侧边栏状态的状态值

  useEffect(() => {
    // 检查 localStorage 中是否有 menuData
      // 新增：获取角色数据，并根据角色找到对应的菜单权限
      const roleData = JSON.parse(localStorage.getItem('roleData')) || DefaultRoleData;
      const userRoleData = roleData.find(roleItem => roleItem.key ===globalContext.user.role);
      const menuPermissions = userRoleData ? userRoleData.menuPermissions : [];

      // 新增：从 localStorage 中获取菜单数据
      const storedMenuData = JSON.parse(localStorage.getItem('menuData')) || null;

      // 新增：根据菜单权限过滤默认菜单数据，得到当前用户的菜单数据
      const filteredMenuData = storedMenuData
          ? storedMenuData.filter(menuItem => menuPermissions.includes(menuItem.key))
          : DefaultMenuData.filter(menuItem => menuPermissions.includes(menuItem.key));

      // 新增：更新菜单数据状态
      setMenuItems(filteredMenuData);
    // ...其他逻辑
  }, []);


  useEffect(() => {
    console.log(globalContext);
    if (!globalContext.user.username) {
      navigate('/login');
    }
  }, [globalContext, navigate]);

  // 点击菜单项的回调函数
  const handleMenuClick = (e) => {
    console.log(e);
    navigate(e.key); // 点击菜单项后跳转到对应路由
  };

  // 切换侧边栏折叠状态的回调函数
  const toggleCollapsed = () => {
    setCollapsed(!collapsed);
  };

  return (
      <Layout style={{ height: '100vh' }}>
        <Header className="auth-header" style={{ backgroundColor: '#FE4E84' }}>
          <DropdownCom />
        </Header >
        <Layout>
          <Sider
              collapsed={collapsed}
              onCollapse={toggleCollapsed}
              className="auth-menu"
              style={{ backgroundColor: '#FFFFFF' }} // 添加滚动条样式
              collapsible={false} // 禁用内置的展开折叠按钮
          >
            <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
              <Button
                  onClick={toggleCollapsed}
                  style={{
                    flex: 1,
                    backgroundColor: 'transparent',
                    border: 'none',
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center'
                  }}
              >
                {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
              </Button>
            </div>
            {renderMenu(menuItems, handleMenuClick)}
          </Sider>
          <Layout>
            <Content style={{ margin: 15 }}>
              <Content className="content-wrapper">
                <Outlet />
              </Content>
            </Content>

          </Layout>
        </Layout>
        {/*<Footer className="auth-footer">*/}
        {/*  *****©{new Date().getFullYear()}*/}
        {/*</Footer>*/}
      </Layout>
  );
}
